package com.buddy.summary.code.algorithm;

import java.util.Stack;

public class Algorithm_02 {
    private Stack<Integer> mainStack = new Stack<>();
    private Stack<Integer> minStack = new Stack<>();

    //入栈 时间复杂度O(1)
    private void push(int ele){
        mainStack.push(ele);
        //如果辅助栈为空,或者新元素小于等于辅助栈顶,则讲新元素压入辅助栈
        if (minStack.isEmpty() || ele <= minStack.peek())
            minStack.push(ele);
    }

    //出栈 时间复杂度O(1)
    private Integer pop(){
        //如果出栈元素和辅助栈顶元素值相等,辅助栈出栈
        if (mainStack.peek().equals(minStack.peek()))
            minStack.pop();
        return mainStack.pop();
    }

    //获取栈的最小元素 时间复杂度O(1)
    private Integer getMin(){
        if (minStack.isEmpty()){
            return null;
        }
        return minStack.peek();
    }

    public static void main(String[] args) {
        Algorithm_02 stack = new Algorithm_02();
        stack.push(4);
        stack.push(9);
        stack.push(7);
        stack.push(3);
        stack.push(8);
        stack.push(5);
        System.out.println(stack.getMin());
        stack.pop();
        stack.pop();
        stack.pop();
        System.out.println(stack.getMin());
    }
}
